import { ref, onMounted } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { getCategoryAPI } from '@/apis/category'

export function useCategory () {
  // 获取商品分类数据
  const categoryData = ref({})
  // 获取路由参数数据
  const route = useRoute()
  // 传递路由参数，默认是id = route.params.id
  const getCategoryData = async (id = route.params.id) => {
    const res = await getCategoryAPI(id)
    categoryData.value = res.result
  }
  onMounted(() => {
    getCategoryData()
  })
  // 在路由更新前，重新请求数据
  onBeforeRouteUpdate((to) => {
    // id = route.params.id具有滞后性
    // 通过to，获取最新路由参数
    getCategoryData(to.params.id)
  })
  return {
    categoryData
  }
}
